<?php

namespace App\Console\Commands;

use App\Constant\RepayConstant;
use App\Constant\ThirdMoneyCode;
use App\Facades\CollectionRequestFacade;
use App\Facades\MoneyPlatformRequestFacade;
use App\Library\ArrayTools\ArrayTools;
use App\Models\Collection\RepayRecord as CollectionRepayRecordModel;
use App\Models\Collection\RepaySummary as CollectionRepaySummaryModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class CollectionCommand extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'collection:cron {action : update|compensate|loanId|test|clearRelief|repairXz} {id?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Collection cron relevant';

    /**
     * The console command action.
     *
     * @var string
     */
    protected $action;

    protected $id;

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $this->initAction();
        $this->runAction();
    }

    /**
     * Description: Initialize command action.
     * Author: Mmy
     */
    protected function initAction()
    {
        $this->action = $this->argument('action');
        $this->id = $this->argument('id');

        if (!in_array($this->action, [
            'update', 'compensate','repayPlanNumber','textCollection','loanId','clearRelief','repairXz'
        ])) {
            $this->error("Invalid argument '{$this->action}'. Expected 'update'.");
            exit(1);
        }
    }

    /**
     * Description: Run action.
     * Author: Mmy
     */
    protected function runAction()
    {
        $this->{$this->action}();
    }

    //todo 销帐 && xz_status = 0 的数据修复
    public function repairXz()
    {

        $this->info('collection repair xz data done');
    }

    /**
     * Description: 销帐状态数据取出 && 同步处理
     * Author: Gxs
     */
    public function compensate()
    {
        foreach (DB::connection('backend')
            ->table('repay_records')
            ->select(['id', 'xz_status', 'result_repay_id'])
            ->where('repay_type', RepayConstant::REPAY_TYPE_FOUR)
            ->where('xz_status', RepayConstant::XZ_STATUS_TWO)
            ->where('result_repay_id', '<>', '')
            ->cursor() as $record
        ) {
            try {
                $get_xz_result = MoneyPlatformRequestFacade::getMoneyRepayResult([
                    'third_repay_id' => $record->result_repay_id,
                    'trade_no' => '',
                ]);
                if (false != $get_xz_result) {
                    $data = $get_xz_result['data'];
                    if (ThirdMoneyCode::RESULT_STATUS_SUCCESS == $data['resultStatus']) {
                        DB::table('repay_records')
                            ->where('id', $record->id)
                            ->update(['xz_status' => RepayConstant::XZ_STATUS_FOUR]);
                    } else if (ThirdMoneyCode::RESULT_STATUS_FAILURE == $data['resultStatus']) {
                        DB::table('repay_records')
                            ->where('id', $record->id)
                            ->update(['xz_status' => RepayConstant::XZ_STATUS_THREE]);
                    } else {

                    }
                }
                $this->info('record_id:'. $record->id . ', 获取销帐结果成功');
            } catch (\Exception $e) {
                Log::debug('collection_compensate_exception', [
                    'record_id' => $record->id,
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                    'message' => $e->getMessage()
                ]);
                $this->info('record_id:'. $record->id . ', 获取销帐结果异常');
            }
        }
        $this->info('collection compensate cron done');
    }

    /**
     * Description: 更新案件
     * Author: Gxs
     */
    public function update()
    {
        $this->info('start');
        $t0 = microtime(true);
        try {
            $current_date = Carbon::now()->format('Y-m-d');
            //查询有逾期的订单id
            CollectionRepayRecordModel::where(function ($query) {
                $query->where('status', RepayConstant::STATUS_ONE);
                $query->orWhere('status', RepayConstant::STATUS_THREE);
            })
                ->where('normal_date', '<', $current_date)
                ->groupBy('summary_id')
                ->chunk(500, function (Collection $summary_collection) use ($current_date, $t0) {
                    $summary_ids = $summary_collection->pluck('summary_id');
                    $summaries = CollectionRepaySummaryModel::leftJoin('repay_records as a', 'repay_summaries.id', '=', 'a.summary_id')
                        ->leftJoin('repay_record_months as b', 'a.id', '=', 'b.record_id')
                        ->leftJoin('repay_record_moneys as c', 'a.id', '=', 'c.record_id')
                        ->leftJoin('repay_record_commons as d', 'a.id', '=', 'd.record_id')
                        ->whereIn('repay_summaries.id', $summary_ids)
                        ->where('a.period', '>', 0)
                        ->select([
                            'repay_summaries.id as summary_id',
                            'repay_summaries.loan_id as case_code',
                            'repay_summaries.uid',
                            'repay_summaries.period',
                            'repay_summaries.period_count',
                            'repay_summaries.amount',
                            'repay_summaries.rate',
                            'repay_summaries.data_type',
                            'repay_summaries.trans_id',
                            'repay_summaries.loan_id',
                            //a 是repay_records
                            'a.id as record_id',
                            'a.amount as record_amount',
                            'a.period as record_period',
                            'a.status as record_status',
                            'a.normal_date',
                            'a.pay_off as pay_off',
                            'a.repay_plan_number as repay_plan_number',
                            'a.created_at as record_create_at',
                            'a.repay_date as repay_date',
                            'a.pay_off as repay_pay_off',
                            //b 是repay_record_months
                            'b.amount as month_amount',
                            'b.status as month_status',
                            //c 是repay_record_moneys
                            'c.fines_money as money_fines',
                            'c.lending_money as money_lending',
                            'c.manage_money as money_manage',
                            'c.status as money_status',
                            //d 是repay_record_commons
                            'd.fines_money as common_fines',
                            'd.lending_money as common_lending', //兼容老数据
                            'd.manage_money as common_manage',
                            'd.status as common_status',
                        ])
                        ->orderBy('a.period', 'asc')
                        ->get();
                    //响应结果数组
                    $req_data = [];
                    $summaries_exchange = ArrayTools::valuesToKey($summaries->toArray(), 'summary_id');
                    //单个还款订单为单位
                    foreach ($summaries_exchange as $key => $records) {
                        if (empty($records))
                            continue;
                        $collection_info = CollectionRepayRecordModel::getCollectionInfo($records);
                        $req_data[] = [
                            'caseMsg' => $collection_info['caseMsg'],
                            'repayPlanList' => $collection_info['repayPlanList'],
                        ];
                    }
                    $collection_request_result = CollectionRequestFacade::sendUpdateCase($req_data);
                    Log::debug('collection_update_command', ['collection_update_command'=> $collection_request_result]);
                    $this->info('批处理时间:' . round(microtime(true) - $t0, 2) . 's');
                });
        } catch (\Exception $e) {
            Log::debug('collection_update_exception', [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'message' => $e->getMessage(),
            ]);
            $this->info('异常信息: Line:' . $e->getLine() . ', File:' . $e->getFile() . ', Message:' . $e->getMessage());
        }
        $time = round(microtime(true) - $t0,2);
        $this->info('done, 执行时间' . $time . 's');
    }

    /**
     * Description: 定时脚本清除减免金额
     * Author: Gxs
     */
    public function clearRelief()
    {
        DB::beginTransaction();
        $info=DB::statement('truncate table repay_relief_records');
        if(!$info){
            DB::rollback();
        }
        DB::commit();
    }
}